from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from typing import Optional

from app.api.deps import get_db
from app.schemas.product import (
    ProductCreate, ProductUpdate, ProductQuery
)
from app.services.product_service import ProductService
from app.utils.response import success, success_pagination, success_list, success_action, not_found, bad_request

router = APIRouter()


@router.post("/", summary="创建商品")
def create_product(
    product_data: ProductCreate,
    db: Session = Depends(get_db)
):
    """
    创建新商品

    - **name**: 商品名称（必填）
    - **price**: 商品价格（必填，大于0）
    - **category_id**: 商品分类ID（必填）
    - **description**: 商品描述（可选）
    - **original_price**: 原价（可选）
    - **stock**: 库存数量（默认为0）
    - **image_url**: 商品图片URL（可选）
    - **is_active**: 是否上架（默认为True）
    - **is_featured**: 是否推荐商品（默认为False）

    注意：SKU会自动生成，无需手动传入
    """
    try:
        product = ProductService.create_product(db, product_data)
        return success(data=product, message="商品创建成功")
    except ValueError as e:
        return bad_request(message=str(e))
    except Exception as e:
        return bad_request(message=f"创建商品失败: {str(e)}")


@router.get("/", summary="获取商品列表")
def get_products(
    name: Optional[str] = Query(None, description="商品名称(模糊搜索)"),
    category_id: Optional[int] = Query(None, description="分类ID"),
    min_price: Optional[float] = Query(None, ge=0, description="最低价格"),
    max_price: Optional[float] = Query(None, ge=0, description="最高价格"),
    is_active: Optional[bool] = Query(None, description="是否上架"),
    is_featured: Optional[bool] = Query(None, description="是否推荐商品"),
    page_no: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页大小"),
    db: Session = Depends(get_db)
):
    """
    获取商品列表（支持分页和筛选）

    - **name**: 商品名称搜索
    - **category_id**: 分类筛选
    - **min_price**: 最低价格筛选
    - **max_price**: 最高价格筛选
    - **is_active**: 是否上架筛选
    - **is_featured**: 是否推荐商品筛选
    - **page_no**: 页码（从1开始）
    - **page_size**: 每页大小（1-100）
    """
    from decimal import Decimal

    query = ProductQuery(
        name=name,
        category_id=category_id,
        min_price=Decimal(str(min_price)) if min_price is not None else None,
        max_price=Decimal(str(max_price)) if max_price is not None else None,
        is_active=is_active,
        is_featured=is_featured,
        page=page_no,
        size=page_size
    )

    try:
        products, total = ProductService.get_products(db, query)
        return success_pagination(
            data=products,
            total=total,
            page_no=page_no,
            page_size=page_size,
            message="获取商品列表成功"
        )
    except Exception as e:
        return bad_request(message=f"获取商品列表失败: {str(e)}")


@router.delete("/{product_id}", summary="删除商品")
def delete_product(
    product_id: int,
    db: Session = Depends(get_db)
):
    """
    删除商品

    - **product_id**: 商品ID
    """
    try:
        success = ProductService.delete_product(db, product_id)
        if not success:
            return not_found(message="商品不存在")

        return success_action(message="商品删除成功")
    except Exception as e:
        return bad_request(message=f"删除商品失败: {str(e)}")


@router.get("/sku/{sku}", summary="根据SKU获取商品")
def get_product_by_sku(
    sku: str,
    db: Session = Depends(get_db)
):
    """
    根据SKU获取商品详情

    - **sku**: 商品SKU
    """
    product = ProductService.get_product_by_sku(db, sku)
    if not product:
        return not_found(message="商品不存在")

    return success(data=product, message="获取商品成功")


@router.get("/featured", summary="获取推荐商品")
def get_featured_products(
    limit: int = Query(10, ge=1, le=50, description="获取数量限制"),
    db: Session = Depends(get_db)
):
    """
    获取推荐商品列表

    - **limit**: 获取数量限制（1-50）
    """
    try:
        products = ProductService.get_featured_products(db, limit)
        return success_list(data=products, message="获取推荐商品成功")
    except Exception as e:
        return bad_request(message=f"获取推荐商品失败: {str(e)}")


@router.get("/category/{category_id}", summary="根据分类获取商品")
def get_products_by_category(
    category_id: int,
    db: Session = Depends(get_db)
):
    """
    根据分类ID获取商品列表

    - **category_id**: 分类ID
    """
    try:
        products = ProductService.get_products_by_category(db, category_id)
        return success_list(data=products, message="获取分类商品成功")
    except Exception as e:
        return bad_request(message=f"获取分类商品失败: {str(e)}")


@router.get("/search", summary="搜索商品")
def search_products(
    keyword: str = Query(..., min_length=1, description="搜索关键词"),
    db: Session = Depends(get_db)
):
    """
    根据关键词搜索商品

    - **keyword**: 搜索关键词（搜索商品名称和描述）
    """
    try:
        products = ProductService.search_products(db, keyword)
        return success_list(data=products, message="搜索商品成功")
    except Exception as e:
        return bad_request(message=f"搜索商品失败: {str(e)}")


@router.put("/{product_id}/stock", summary="更新商品库存")
def update_product_stock(
    product_id: int,
    quantity: int = Query(..., description="库存变化量（正数为增加，负数为减少）"),
    db: Session = Depends(get_db)
):
    """
    更新商品库存

    - **product_id**: 商品ID
    - **quantity**: 库存变化量（正数为增加，负数为减少）
    """
    try:
        # 首先检查商品是否存在
        existing_product = ProductService.get_product_by_id(db, product_id)
        if not existing_product:
            return not_found(message=f"商品ID {product_id} 不存在")

        # 调用服务层更新库存
        product = ProductService.update_stock(db, product_id, quantity)
        if not product:
            return not_found(message="商品不存在")

        return success(data=product, message="库存更新成功")
    except ValueError as e:
        return bad_request(message=str(e))
    except Exception as e:
        # 添加更详细的错误信息
        import traceback
        error_detail = f"更新库存失败: {str(e)}\n详细信息: {traceback.format_exc()}"
        return bad_request(message=error_detail)


@router.get("/{product_id}", summary="获取商品详情")
def get_product(
    product_id: int,
    db: Session = Depends(get_db)
):
    """
    根据商品ID获取商品详情

    - **product_id**: 商品ID
    """
    product = ProductService.get_product_by_id(db, product_id)
    if not product:
        return not_found(message="商品不存在")

    return success(data=product, message="获取商品成功")


@router.put("/{product_id}", summary="更新商品")
def update_product(
    product_id: int,
    product_data: ProductUpdate,
    db: Session = Depends(get_db)
):
    """
    更新商品信息

    - **product_id**: 商品ID
    - 所有字段都是可选的，只更新提供的字段
    """
    try:
        product = ProductService.update_product(db, product_id, product_data)
        if not product:
            return not_found(message="商品不存在")

        return success(data=product, message="商品更新成功")
    except ValueError as e:
        return bad_request(message=str(e))
    except Exception as e:
        return bad_request(message=f"更新商品失败: {str(e)}")